import { addCarModelsAPI, deleteCarModelsAPI, fetchCarModelsAPI, fetchCarModelsListAPI, fetchCarModelsListTypeAPI, updateCarModelsAPI } from '@/api/vehicle/carModelsAPI'

const actions = {
  /*
  *获取车辆类型分页数据的action
  *  */
  async fetchCarModelsListAction(context, pageParams) {
    const { data } = await fetchCarModelsListAPI(pageParams)
    context.commit('setCarModelsListAction', data)
    return data.items
  },

  /*
  * 删除车型的action
  *  */
  async deleteCarModelsAction(context, id) {
    await deleteCarModelsAPI(id)
    return '删除车型成功'
  },

  /*
  * 批量删除车型的action
  *  */
  handleDeleteAllAction(context, ids) {
    const promiseArray = []
    ids.forEach((id) => promiseArray.push(context.dispatch('deleteCarModelsAction', id)))
    return Promise.all(promiseArray)
  },

  /*
  *
  * 添加车型的action
  *  */
  async addCarModelsAction(context, formData) {
    await addCarModelsAPI(formData)
    return '添加车型成功'
  },

  /*
  * 更新车型的action
  *  */
  async updateCarModelsAction(context, id) {
    await updateCarModelsAPI(id)
    return '编辑车型成功'
  },

  /*
  * 获取车辆详情的action
  *  */
  async fetchCarModelsAction(context, id) {
    const { data } = await fetchCarModelsAPI(id)
    return data
  },

  /*
  * 获取车辆类型信息列表的action
  *  */
  async fetchCarModelsListTypeAction(context) {
    const { data } = await fetchCarModelsListTypeAPI()
    context.commit('setCarModelsListTypeMutation', data.flat())
  }
}
const mutations = {
  /*
  *设置车辆类型分页数据的mutation
  *  */
  setCarModelsListAction(state, { counts, items }) {
    state.counts = Number(counts)
    state.carModelsList = items
  },
  /*
  * 设置车辆类型信息列表的mutation
  *  */
  setCarModelsListTypeMutation(state, listType) {
    state.carModelsListType = listType
  }
}
const state = () => {
  return {
    counts: 0,
    carModelsList: [],
    carModelsListType: []
  }
}

export default {
  actions,
  mutations,
  state,
  namespaced: true
}
